import atexit
from typing import TypeVar, Type
from config import get_id
from config import logger

T = TypeVar('T')


class DB():

    def __init__(self):
        self.transaction: bool = False
        self.transaction_id: int = None


    """
        获取数据库连接
    """
    def get_connect(self):
        raise NotImplemented

    """
        获取数据库游标
    """
    def get_cursor(self):
        raise NotImplemented

    def close(self):
        raise NotImplemented

    """
        执行SQL语句，返回结果集
    """
    def execute(self, sql: str, params: tuple = None) -> list:
        raise NotImplemented

    """
        执行SQL，获取一条数据，用对象接收
    """
    def get_one(self, sql: str, class_type: Type[T] = None, params: tuple = None) -> T:
        raise NotImplemented

    """
        执行SQL，获取所有数据，用对象接收
    """
    def get_list(self, sql: str, class_type: Type[T] = None, params: tuple = None) -> list:
        raise NotImplemented

    """
        执行一条insert的SQL，返回受影响行数
    """
    def insert_one(self, sql: str, params: tuple = None) -> int:
        raise NotImplemented

    """
        执行insert的SQL，插入多条数据，返回受影响行数
    """
    def insert_many(self, sql: str, params_list: list[tuple] = None) -> int:
        raise NotImplemented

    """
        执行一条update的SQL，返回受影响行数
    """
    def update_one(self, sql: str, params: tuple = None) -> int:
        raise NotImplemented

    """
        执行一条delete的SQL，返回受影响行数
    """
    def delete(self, sql: str, params: tuple = None) -> int:
        raise NotImplemented

    """
        将字典转换成自定义类的对象
    """
    def create_instance_from_type(self, data_dict: dict, class_type: Type[T]) -> T:
        data_object = class_type(**data_dict)
        return data_object

    """
        将自定义类的对象的值按照定义顺序转换成元组
        此函数依赖Python的版本最低为3.7，否则无法保证元组中元素的顺序
    """
    def object_to_tuple(self, obj: T) -> tuple:
        return obj.__dict__.values()

    """
        开启事务
    """
    def open_transaction(self):
        self.transaction = True
        self.transaction_id = get_id()
        logger.info(f"已开启事务，事务ID: {self.transaction_id}")

    """
        提交事务
    """
    def commit(self):
        raise NotImplemented

    """
        回滚事务
    """
    def rollback(self):
        raise NotImplemented

    """
        事务的装饰器实现
    """
    def transactional(self):
        raise NotImplemented

    """
        关闭事务
    """
    def close_transaction(self):
        transaction_id: int = self.transaction_id
        self.transaction = False
        self.transaction_id = None
        self.rollback()
        if transaction_id != None:
            logger.info(f"事务ID: {transaction_id} 已关闭")

    """
        获取整型的雪花ID
    """
    def get_id(self) -> int:
        return get_id()


